package com.kizuki.thread;

import org.junit.Test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 方法\处理方式	抛出异常	    返回特殊值	一直阻塞	 超时退出
 * 插入方法	    add(e)	    offer(e)	put(e)	 offer(e,time,unit)
 * 移除方法	    remove()	poll()	    take()	 poll(time,unit)
 * 检查方法	    element()	peek()	    -	     -
 */
public class TestBlockQueue {

    @Test
    public void test1(){ // 抛出异常
        ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue<>(1);

        System.out.println(arrayBlockingQueue.add(1));
//        System.out.println(arrayBlockingQueue.add(2)); // java.lang.IllegalStateException: Queue full

        System.out.println(arrayBlockingQueue.element()); // 队首元素

        System.out.println(arrayBlockingQueue.remove());
//        System.out.println(arrayBlockingQueue.remove()); // java.util.NoSuchElementException
    }

    @Test
    public void test2(){ // 不抛出异常, 有返回值
        ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue<>(1);

        System.out.println(arrayBlockingQueue.offer(1));
        System.out.println(arrayBlockingQueue.offer(2)); // false

        System.out.println(arrayBlockingQueue.peek()); // 队首元素

        System.out.println(arrayBlockingQueue.poll());
        System.out.println(arrayBlockingQueue.poll()); // null
    }

    @Test
    public void test3() throws InterruptedException { // 一直阻塞
        ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue<>(1);

        arrayBlockingQueue.put(1);
//        arrayBlockingQueue.put(2);

        System.out.println(arrayBlockingQueue.take());
//        System.out.println(arrayBlockingQueue.take());
    }

    @Test
    public void test4() throws InterruptedException { // 阻塞,超时退出
        ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue<>(1);

        arrayBlockingQueue.offer(1, 2, TimeUnit.SECONDS);
//        arrayBlockingQueue.offer(2, 2, TimeUnit.SECONDS);

        System.out.println(arrayBlockingQueue.poll(2, TimeUnit.SECONDS));
        System.out.println(arrayBlockingQueue.poll(2, TimeUnit.SECONDS));
    }

}
